package com.yequan.thread.countdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author yq
 * @date 2020/09/03
 */
public class GameLoad {

    private static ExecutorService threadPool = Executors.newFixedThreadPool(5);
    private static CountDownLatch heroLatch = new CountDownLatch(5);
    private static CountDownLatch systemLatch = new CountDownLatch(1);
    private static String[] heroes = {"凯", "甄姬", "孙尚香", "牛魔", "孙悟空"};

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 5; i++) {
            threadPool.submit(new Hero(heroes[i], heroLatch, systemLatch));
        }
        System.out.println("===等待英雄加载游戏===");
        heroLatch.await();
        System.out.println("===英雄已全部进入游戏===");
        systemLatch.countDown();
        threadPool.shutdown();
    }

    static class Hero implements Runnable {

        private String hero;
        private CountDownLatch heroLatch;
        private CountDownLatch systemLatch;

        public Hero(String hero, CountDownLatch heroLatch, CountDownLatch systemLatch) {
            this.hero = hero;
            this.heroLatch = heroLatch;
            this.systemLatch = systemLatch;
        }

        @Override
        public void run() {
            try {
                System.out.println(hero + "开始加载...");
                TimeUnit.SECONDS.sleep((long) (Math.random() * 10));
                heroLatch.countDown();
                System.out.println(hero + "加载完成");
                systemLatch.await();
                System.out.println(hero + "开始游戏");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
